// 如果你想让这个组件成为客户端组件：  
'use client';
import { useEffect, useMemo, useRef, useState } from "react";
import { Affix, Button, message } from 'antd'
import { ButtonEnum, generateDireaction, generateNumber, generateWeightedRandomNumber, getRandomPoint, mat2gray, renderE } from "../utils/tool";
import useGamePad from "../gamepade/useGamePad";

type TestItem = {
    direction: number, frequency: number
}

// 手柄链接
// 测试开始
export default function Dom() {
    const { timestamp, button } = useGamePad();
    const frequency = useRef(30);
    const direction: any = useRef(1);
    const opacity: any = useRef(0.2);
    const testList = useRef<Array<TestItem>>([]);
    const feedbackList = useRef<Array<TestItem & { correct: boolean }>>([]);
    var { context, canvas } = useMemo(() => {
        if (window && document && document.getElementById('canvas6')) {
            const _canvas = document.getElementById('canvas6') as HTMLCanvasElement;;
            // 设置canvas的宽度和高度  
            const _context = _canvas.getContext('2d') as CanvasRenderingContext2D
            _context.clearRect(0, 0, _canvas.width, _canvas.height);

            return { canvas: _canvas, context: _context }
        }
        return {}
    }, []);
    const [state, _setState] = useState({
        begin: false,
    });
    const setState = (params: { [key: string]: any }) => {
        _setState((_state) => ({ ..._state, ...params }));
    };
    const { begin } = state;
    // 确保渲染上下文与canvas的尺寸匹配  
    // context.scale(canvas.width / window.innerWidth, canvas.height / window.innerHeight);

    function getCos(_frequency: number, _direction?: number, _opacity?: number, temp = false) {
        _direction = _direction || direction.current as number;
        _opacity = _opacity || opacity.current;
        _opacity = parseFloat((_opacity as any).toFixed(3));
        // _opacity = _opacity || generateWeightedRandomNumber(1, 10) / 10;
        testList.current.push({
            direction: _direction,
            frequency: _frequency
        })
        if (!temp) {
            frequency.current = _frequency;
            direction.current = _direction
            opacity.current = _opacity
        }
        mat2gray(_frequency, _direction, _opacity, { context, canvas } as any)
    }
    useEffect(() => {
        if (button == ButtonEnum.START) {
            setState({
                begin: true,
            })
            setTimeout(() => {
                getCos(30, direction.current, 0.2)
            }, 1000);
        } else if (testList.current.length) {
            let currentE = testList.current[testList.current.length - 1];
            if ([ButtonEnum.A, ButtonEnum.B, ButtonEnum.X, ButtonEnum.Y].includes(button)) {
                let lastFeed = feedbackList.current[feedbackList.current.length - 1];
                let correct = currentE.direction == ({ [ButtonEnum.Y]: 2, [ButtonEnum.A]: 2, [ButtonEnum.X]: 1, [ButtonEnum.B]: 1, })[button]
                feedbackList.current.push({
                    ...currentE,
                    correct: correct
                });
                if (correct) {
                    getCos(lastFeed?.correct === false ? frequency.current : frequency.current - 1, generateNumber(1, 2), opacity.current);
                } else {
                    message.open({
                        icon: null,
                        content: <span style={{ fontSize: '50px' }}>{currentE.frequency}, {({ 1: '横', 2: '竖' })[currentE.direction]}, {opacity.current}</span>
                    })
                    getCos(frequency.current + 1, generateNumber(1, 2), opacity.current)
                }
            }
            if ([ButtonEnum.LEFT, ButtonEnum.BOTTOM, ButtonEnum.TOP, ButtonEnum.RIGHT].includes(button) && testList.current.length) {
                let correct = currentE.direction == ({ [ButtonEnum.TOP]: 2, [ButtonEnum.BOTTOM]: 2, [ButtonEnum.LEFT]: 1, [ButtonEnum.RIGHT]: 1, })[button]
                feedbackList.current.push({
                    ...currentE,
                    correct: correct
                });
                if (feedbackList.current.length % 30 === 0) {
                    getCos(80, generateNumber(1, 2), 0.7, true)
                } else {
                    getCos(frequency.current, generateNumber(1, 2), opacity.current)
                }
            }
            // 提升频率
            if (button == ButtonEnum.CIRCLER) {
                let _frequency = frequency.current
                if (_frequency < 11) {
                    _frequency = _frequency + 1;

                } else {
                    _frequency = _frequency + 10;

                }
                // 在这里执行你想要的代码  
                // mat2gray(frequency, opacity, direction);
                getCos(_frequency, direction.current, opacity.current)
            }
            // 降低评率
            if (button == ButtonEnum.CIRCLEL) {
                let _frequency = frequency.current

                if (_frequency < 11) {
                    _frequency = _frequency - 1;
                } else {
                    _frequency = _frequency - 10;
                }
                getCos(_frequency, direction.current, opacity.current)
            }
            // 提高对比度
            if (button == ButtonEnum.L1) {
                let _opacity = opacity.current
                if (_opacity >= 1) {
                    message.open({
                        icon: null,
                        content: <span style={{ fontSize: '50px' }}>{currentE.frequency}, {({ 1: '横', 2: '竖' })[currentE.direction]}, {opacity.current}</span>
                    })
                } else {
                    if (_opacity >= 0.1) {
                        _opacity = _opacity + 0.1;
                    } else {
                        _opacity = _opacity + 0.1 / 10;
                    }
                    // 在这里执行你想要的代码  
                    getCos(frequency.current, direction.current, _opacity)
                }
            }
            // 降低
            if (button == ButtonEnum.R1) {
                let _opacity = opacity.current
                if (_opacity <= 0) {
                    message.open({
                        icon: null,
                        content: <span style={{ fontSize: '50px' }}>{currentE.frequency}, {({ 1: '横', 2: '竖' })[currentE.direction]}, {opacity.current}</span>
                    })
                } else {
                    if (_opacity <= 0.1) {
                        _opacity = _opacity - 0.1 / 10;
                    } else {
                        _opacity = _opacity - 0.1;
                    }
                    // 在这里执行你想要的代码  
                    getCos(frequency.current, direction.current, _opacity)
                }
            }
            if (button == ButtonEnum.SELECT) {
                message.open({
                    icon: null,
                    content: <span style={{ fontSize: '80px' }}>{currentE.frequency}, {({ 1: '横', 2: '竖' })[currentE.direction]}, {opacity.current}</span>
                })
            }
            if (button == ButtonEnum.R2) {
                message.open({
                    icon: null,
                    content: <span style={{ fontSize: '80px' }}>您做对{feedbackList.current.filter(item => item.correct)?.length}个， 错了{feedbackList.current.filter(item => item.correct === false)?.length}个</span>
                })
            }
        }
    }, [timestamp])

    return <>
        {begin ? <> </> : <div style={{ textAlign: 'center', opacity: 'absolute', top: '1rem', zIndex: 1 }}>
            <Button size="large" type="primary" onClick={() => {
                setState({
                    begin: true,
                })
                setTimeout(() => {
                    getCos(50)
                }, 1000);
            }}>开始测试</Button>
        </div>}
    </>
}